package com.zatech.cgnci.project.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zatech.cgnci.project.base.context.UserContext;
import com.zatech.cgnci.project.base.utils.VerifyUtils;
import com.zatech.cgnci.project.dto.CgnciApprovalInfoQueryDTO;
import com.zatech.cgnci.project.entity.UserEntity;
import com.zatech.cgnci.project.service.CgnciApprovalConfigService;
import com.zatech.cgnci.project.service.CgnciApprovalInfoService;
import com.zatech.cgnci.project.vo.CgnciApprovalConfigVO;
import com.zatech.cgnci.project.vo.CgnciApprovalInfoPageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批流程发起表 前端控制器
 * </p>
 *
 * @author Generator
 * @since 2024-12-17
 */
@RestController
@RequestMapping("/api/approval-info")
@RequiredArgsConstructor
@Api(produces = "application/json", tags = "工作台api接口文档")
public class CgnciApprovalInfoController {

    private final CgnciApprovalInfoService approvalInfoService;

    private final CgnciApprovalConfigService approvalConfigService;


    @PostMapping("/page")
    @ApiOperation(value = "分页列表查询")
    public IPage<CgnciApprovalInfoPageVO> page(@RequestBody CgnciApprovalInfoQueryDTO queryDTO) {
        // 获取当前登录用户
        UserEntity user = UserContext.getUser();
        // 根据taskTypeCode 查询关联的taskTypeCodeList
        if (VerifyUtils.isNotEmpty(queryDTO.getTaskTypeCode())) {
            List<String> taskTypeCodeList = approvalConfigService.listTaskTypeCode(queryDTO.getTaskTypeCode());
            queryDTO.setTaskTypeCodeList(taskTypeCodeList);
        }
        queryDTO.setUserCode(user.getUsercode());
        IPage<CgnciApprovalInfoPageVO> page = approvalInfoService.pageApprovalInfo(queryDTO);
        List<CgnciApprovalInfoPageVO> records = page.getRecords();
        if (VerifyUtils.isNotEmpty(records)) {
            records.forEach(record -> record.setHasEdit(VerifyUtils.isNotEmpty(record.getCurrentApproverAndName()) && record.getCurrentApproverAndName().contains(user.getNameAndCode())));
        }
        return page;
    }

    @GetMapping("/listTaskType")
    @ApiOperation(value = "获取任务类型下拉")
    public List<CgnciApprovalConfigVO> listTaskType() {
        List<CgnciApprovalConfigVO> list = approvalConfigService.listTaskType();
        Map<String, CgnciApprovalConfigVO> uniqueTaskTypeMap = list.stream()
                .collect(Collectors.toMap(CgnciApprovalConfigVO::getTaskType, config -> config, (existing, replacement) -> existing));
        return new ArrayList<>(uniqueTaskTypeMap.values());
    }

}

